package com.zm.demo.netty.client.http;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.net.URI;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * @author z01140
 * @Package: com.zm.demo.netty.client.http
 * @Description:
 * @CreateDate 2023/8/31 13:00
 * @UpdateDate 2023/8/31 13:00
 */
public class HttpClientHandler extends SimpleChannelInboundHandler<FullHttpResponse> {

    private String param;

    public HttpClientHandler(){

    }
    public HttpClientHandler(String param){
        this.param = param;
    }
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        URI uri = new URI("http://127.0.0.1:8888");
        String msg = "Are you ok?";
        FullHttpRequest fullHttpRequest = new DefaultFullHttpRequest(
                HttpVersion.HTTP_1_1, HttpMethod.GET, uri.toASCIIString(), Unpooled.copiedBuffer(param.getBytes(StandardCharsets.UTF_8)));
        fullHttpRequest.headers().set(HttpHeaderNames.CONTENT_LENGTH, fullHttpRequest.content().readableBytes());

        // 发送http请求
        System.out.println("发送消息:" + param);
        ctx.channel().writeAndFlush(fullHttpRequest);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) throws Exception {
            System.out.println("收到消息："  + msg.content().toString(CharsetUtil.UTF_8));
    }
}
